package com.ccdc.cbpc.bigdata.common.util;

import com.ccdc.cbpc.bigdata.common.util.security.Md5Util;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.UUID;

/**
 * ID生成算法
 * @author zhangdong
 * @date 2021-07-19
 */
@Slf4j
public class IDGenerateUtil {
    public static String generateMD5Key(String... fieldsData ){
        return Md5Util.encodeMoreDataByMD5(fieldsData);
    }
    public static String generateMD5Key(char splitStr,String... fieldsData){
        return Md5Util.encodeMoreDataByMD5(splitStr,fieldsData);
    }
    /**
     * 获取36位UUID 含"-"
     * @return
     */
    public static String getUUID36(){
        return UUID.randomUUID().toString();
    }
    /**
     * 获取36位UUID
     * @return
     */
    public static String getUUID32(){
        return getUUID36().replaceAll("-","");
    }

    /**
     * 获得一个UUIDKey
     *
     * @return String UUID
     */
    public static String generateUUIDKey() {
        String s = UUID.randomUUID().toString().toUpperCase();
        // 去掉“-”符号
        return s.replace("-", "");
    }

    /**
     * 获得指定数目的UUID
     *
     * @param number
     *            int 需要获得的UUID数量
     * @return String[] UUID数组
     */
    public static String[] getUUIDKeys(int number) {
        if (number < 1) {
            return null;
        }
        String[] ss = new String[number];
        for (int i = 0; i < number; i++) {
            ss[i] = generateUUIDKey();
        }
        return ss;
    }

    /**
     * 获取指定位数的随机数
     * @param length
     * @return
     */
    public static String getRadom(int length) {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        while (length > 0 ) {
            sb.append(random.nextInt(10));
            length--;
        }
        return sb.toString();
    }

    /**
     * 雪花算法
     */
    public static class SnowFlakeUtil{
        private final long id;
        /**
         * 时间起始标记点，作为基准，一般取系统的最近时间
         */
        private final long epoch = 1524291141010L;
        /**
         * 机器标识位数
         */
        private final long workerIdBits = 10L;
        /**
         * 机器ID最大值: 1023
         */
        private final long maxWorkerId = -1L ^ -1L << this.workerIdBits;
        /**
         * 0，并发控制
         */
        private long sequence = 0L;
        /**
         * 毫秒内自增位
         */
        private final long sequenceBits = 12L;

        /**
         * 12
         */
        private final long workerIdShift = this.sequenceBits;
        /**
         * 22
         */
        private final long timestampLeftShift = this.sequenceBits + this.workerIdBits;
        /**
         * 4095,111111111111,12位
         */
        private final long sequenceMask = -1L ^ -1L << this.sequenceBits;
        private long lastTimestamp = -1L;

        private SnowFlakeUtil(long id) {
            if (id > this.maxWorkerId || id < 0) {
                throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", this.maxWorkerId));
            }
            this.id = id;
        }

        public synchronized long nextId() {
            long timestamp = timeGen();
            if (this.lastTimestamp == timestamp) {
                //如果上一个timestamp与新产生的相等，则sequence加一(0-4095循环); 对新的timestamp，sequence从0开始
                this.sequence = this.sequence + 1 & this.sequenceMask;
                if (this.sequence == 0) {
                    // 重新生成timestamp
                    timestamp = this.tilNextMillis(this.lastTimestamp);
                }
            } else {
                this.sequence = 0;
            }

            if (timestamp < this.lastTimestamp) {
                log.warn(String.format("clock moved backwards.Refusing to generate id for %d milliseconds", (this.lastTimestamp - timestamp)));
                return -1;
            }

            this.lastTimestamp = timestamp;
            return timestamp - this.epoch << this.timestampLeftShift | this.id << this.workerIdShift | this.sequence;
        }

        private static SnowFlakeUtil flowIdWorker = new SnowFlakeUtil(1);
        public static SnowFlakeUtil getFlowIdInstance() {
            return flowIdWorker;
        }

        /**
         * 等待下一个毫秒的到来, 保证返回的毫秒数在参数lastTimestamp之后
         */
        private long tilNextMillis(long lastTimestamp) {
            long timestamp = timeGen();
            while (timestamp <= lastTimestamp) {
                timestamp = timeGen();
            }
            return timestamp;
        }
        public static long getId(){
            return SnowFlakeUtil.getFlowIdInstance().nextId();
        }
        public static String getIdStr(){
            return getId()+"";
        }
        /**
         * 获得系统当前毫秒数
         */
        private static long timeGen() {
            return System.currentTimeMillis();
        }
    }
    public static void main(String[] args) {
        System.out.println(getUUID36());
        System.out.println(getUUID32());
        System.out.println(getRadom(20));
        System.out.println(SnowFlakeUtil.getIdStr());
    }
}
